import {
  _decorator,
  CCInteger,
  Component,
  Node,
  randomRange,
  tween,
  UITransform,
  Vec3,
} from "cc";
import { SunManager } from "./manager/SunManager";
const { ccclass, property } = _decorator;

@ccclass("Sun")
export class Sun extends Component {
  @property(CCInteger)
  point: number = 0;

  protected onLoad(): void {
    this.node.on(Node.EventType.MOUSE_DOWN, this.onMouseDown, this);
  }

  protected onDestroy(): void {
    this.node.off(Node.EventType.MOUSE_DOWN, this.onMouseDown, this);
  }

  /**
   * 自然光下落
   */
  linearTo(xPosition: number) {
    const targetPos = new Vec3(xPosition, randomRange(-740, -210), 0);
    tween(this.node)
      .to(3.2, { position: targetPos }, { easing: "linear" })
      .start();
  }

  /**
   * 从向日葵产生的
   */
  jumpTo() {
    const startPos = this.node.position;
    const middlePos = startPos.clone().add(new Vec3(0, 100, 0));
    const targetPos = startPos
      .clone()
      .add(new Vec3(randomRange(-70, 70), 0, 0));

    tween(this.node)
      .to(0.5, { position: middlePos }, { easing: "expoInOut" })
      .to(0.5, { position: targetPos }, { easing: "linear" })
      .start();
  }

  onMouseDown() {
    const targetWorldPos = SunManager.Instance.sumPointLabel.node
      .getComponent(UITransform)
      .convertToWorldSpaceAR(new Vec3(0, 0, 0));
    const targetLocalPos = this.node.parent
      .getComponent(UITransform)
      .convertToNodeSpaceAR(targetWorldPos);
    tween(this.node)
      .to(1, {
        position: targetLocalPos,
      })
      .call(() => {
        SunManager.Instance.addSun(this.point);
        this.node.destroy();
      })
      .start();
  }
}
